﻿#include "../HUICLogin.h"
#include "../../HCustomWidgets/HComponent.h"
#include "../../include/HSettingConfigOperator.h"
#include "../../HCustomWidgets/HExitPanel.h"


HUICLogin::HUICLogin(QWidget *parent)
    :QWidget(parent)
{
    g_strAppPath = QApplication::applicationDirPath();
    m_nCount = 5;
	QHash<QString,QString> hashVersion;
    HSettingConfigOperator::readConfig(hashVersion,QApplication::applicationDirPath() + XMLRELATIONPATH + "versionConfig.xml");
	QString strVersion = hashVersion.value("version");
	m_strVersion = strVersion;

	m_hashIndexToUserInfo.clear();
    readConfig();
    initControlSize();
    initUI();
}

HUICLogin::~HUICLogin()
{

}

void HUICLogin::setRememerCount(int nCount)
{
    m_nCount = nCount;
}

void HUICLogin::setWarning(QString strWarning)
{
	m_plblWarning->setText(strWarning);
	m_plblWarning->show();
}

QString HUICLogin::getUserName()
{
    return m_pcmbUser->currentText();
}

void HUICLogin::setUserName(QString strUserName)
{
	m_plecmbUser->setText(strUserName);
}

QString HUICLogin::getPassword()
{
    return m_plePassword->text();
}

void HUICLogin::setPassword(QString strPassword)
{
	m_plePassword->setText(strPassword);
}

QString HUICLogin::getWarning()
{
	return m_plblWarning->text();
}

void HUICLogin::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    QWidget::paintEvent(event);
}

void HUICLogin::keyPressEvent(QKeyEvent *event)
{
	if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
	{
	    m_ppbLogin->clicked();
	}
	QWidget::keyPressEvent(event);
}

void HUICLogin::initControlSize()
{
    m_nLoginBtnHeight = 60;
    m_nLayoutSpacing = 15;
    m_nMainLayoutL = 30;
    m_nMainLayoutU = 25;
    m_nMainLayoutR = 30;
    m_nMainLayoutB = 40;
    m_nSubMainLayoutL = 22;
    m_nSubMainLayoutU = 0;
    m_nSubMainLayoutR = 22;
    m_nSubMainLayoutB = 0;
}

void HUICLogin::initUI()
{
    this->setObjectName("login_wnd_mainPanel");
    m_pvblMain = new QVBoxLayout();
    m_pvblMain->setContentsMargins(m_nMainLayoutL,m_nMainLayoutU,m_nMainLayoutR,m_nMainLayoutB);
    m_pvblMain->setSpacing(m_nLayoutSpacing);

    m_pvblSubMain = new QVBoxLayout();
    m_pvblSubMain->setSpacing(m_nLayoutSpacing);
    m_pvblSubMain->setContentsMargins(m_nSubMainLayoutL,m_nSubMainLayoutU,m_nSubMainLayoutR,m_nSubMainLayoutB);

    m_phblPanelControl = new QHBoxLayout();
    m_phblPanelControl->setSpacing(0);
    m_phblPanelControl->setContentsMargins(0,0,0,0);

    m_ppbSetting = new QPushButton(this);
    m_ppbSetting->setFixedSize(NLOGINPANELCONTROLBTNWIDTH,NLOGINPANELCONTROLBTNWIDTH);
    m_ppbSetting->setObjectName("login_btn_setting");

    m_ppbMin = new QPushButton(this);
    m_ppbMin->setFixedSize(NLOGINPANELCONTROLBTNWIDTH,NLOGINPANELCONTROLBTNWIDTH);
    m_ppbMin->setObjectName("login_btn_min");

    m_ppbClose = new QPushButton(this);
    m_ppbClose->setFixedSize(NLOGINPANELCONTROLBTNWIDTH,NLOGINPANELCONTROLBTNWIDTH);
    m_ppbClose->setObjectName("lgoin_btn_close");

    m_plblLogo = new QLabel(this);
    m_plblLogo->setPixmap(QPixmap(g_strAppPath + g_strImageRelationPath + "HIDI_LOGIN_LOGO_NOR.png"));

    m_lvUser = new QListView();
    m_lvUser->setObjectName("login_lv_user");
    m_lvUser->setFocusPolicy(Qt::NoFocus);
    m_lvUser->setItemDelegate(new HNoFocusFrameDelegate(m_lvUser));

    m_pcmbUser = new HComboBox(this);
    m_pcmbUser->setObjectName("login_cmb_user");
    m_pcmbUser->setEditable(true);
    m_pcmbUser->setFixedHeight(NCONTROLLOGINHEIGHT);
    m_pcmbUser->setView(m_lvUser);
    m_pcmbUser->clear();
	QStringList strLitUserName;
    for(int cmbIndex = 0; cmbIndex < m_hashIndexToUserInfo.count(); cmbIndex ++)
	{
		QPair<QString,QString> pairUserNameAndPass = m_hashIndexToUserInfo.value(cmbIndex);
		QString strUserName = pairUserNameAndPass.first;
		QString strPassword = pairUserNameAndPass.second;
		strLitUserName.append(strUserName);
	}
    m_pcmbUser->addItems(strLitUserName);

    m_plecmbUser = new HLineEdit(m_pcmbUser);
    m_plecmbUser->setPlaceholderText(QString::fromLocal8Bit("请输入用户名"));
    m_plecmbUser->setObjectName("login_le_input");
    m_pcmbUser->setLineEdit(m_plecmbUser);


    m_plePassword = new HLineEdit(this);
    m_plePassword->setObjectName("login_le_input");
    m_plePassword->setFixedHeight(NCONTROLLOGINHEIGHT);
    m_plePassword->setEchoMode(QLineEdit::Password);
    m_plePassword->setPlaceholderText(QString::fromLocal8Bit("请输入密码"));

    m_pckbRPassword = new QCheckBox(this);
    m_pckbRPassword->setObjectName("login_ckb_remember_password");
    m_pckbRPassword->setText(QString::fromLocal8Bit("记住密码"));

    m_plblWarning = new QLabel(this);
    m_plblWarning->setObjectName("login_lbl_warning");
    m_plblWarning->setText(QString::fromLocal8Bit(""));

    m_ppbLogin = new QPushButton(this);
    m_ppbLogin->setObjectName("login_pb_login");
    m_ppbLogin->setText(QString::fromLocal8Bit("登录"));
    m_ppbLogin->setFixedHeight(m_nLoginBtnHeight);

    m_plblVersion = new QLabel(this);
    m_plblVersion->setObjectName("login_lbl_version");
    m_plblVersion->setText(QString::fromLocal8Bit("版本号:") + m_strVersion);
    m_plblVersion->setAlignment(Qt::AlignHCenter);


    m_phblPanelControl->addStretch(100);
    m_phblPanelControl->addWidget(m_ppbSetting);
    m_phblPanelControl->addWidget(m_ppbMin);
    m_phblPanelControl->addWidget(m_ppbClose);

    m_pvblMain->addLayout(m_phblPanelControl,1);

    m_pvblSubMain->addStretch(5);
    m_pvblSubMain->addWidget(m_plblLogo,1,Qt::AlignHCenter);
    m_pvblSubMain->addStretch(5);
    m_pvblSubMain->addWidget(m_pcmbUser,1);
    m_pvblSubMain->addWidget(m_plePassword,1);
    m_pvblSubMain->addWidget(m_pckbRPassword,1);
    m_pvblSubMain->addStretch(1);
    m_pvblSubMain->addWidget(m_plblWarning,1,Qt::AlignHCenter);
    m_pvblSubMain->addWidget(m_ppbLogin,1);
    m_pvblSubMain->addStretch(10);
    m_pvblSubMain->addWidget(m_plblVersion,1);

    m_pvblMain->addLayout(m_pvblSubMain);

    this->setLayout(m_pvblMain);

   // connect(m_plecmbUser,SIGNAL(sigFocusStateChanged(bool)),this,SLOT(sltLineEditFocusStateChanged(bool)));
	connect(m_plecmbUser,SIGNAL(textChanged(QString)),this,SLOT(sltUserNameTextChanged(QString)));
    connect(m_plePassword,SIGNAL(sigFocusStateChanged(bool)),this,SLOT(sltLineEditFocusStateChanged(bool)));
    connect(m_pcmbUser,SIGNAL(sigFocusStateChanged(bool)),this,SLOT(sltComboBoxFocusStateChanged(bool)));
	connect(m_pcmbUser,SIGNAL(activated(QString)),this,SLOT(sltComboBoxIndexChanged(QString)));

    connect(m_ppbSetting,SIGNAL(clicked()),this,SIGNAL(sigSettingButtonClicked()));
    connect(m_ppbLogin,SIGNAL(clicked()),this,SLOT(sltLoginBtnClicked()));

    connect(m_ppbMin,SIGNAL(clicked()),this,SIGNAL(sigMinBtnClicked()));
    //connect(m_ppbClose,SIGNAL(clicked()),qApp,SLOT(quit()));
	connect(m_ppbClose,SIGNAL(clicked()),this,SLOT(sltCloseBtnClicked()));

	if(m_pcmbUser->count() > 0)
	{
		QString strFirstName = m_pcmbUser->itemText(0);
	    m_pcmbUser->activated(strFirstName);
	}
}

bool HUICLogin::readConfig()
{
	QString strFile = g_strAppPath + XMLRELATIONPATH + "userNameConfig.xml";

	QFile file(strFile);
	if(!file.open(QIODevice::ReadOnly))
	{
		return false;
	}

	QDomDocument doc;

	
	QByteArray fileContent = file.readAll();
	QByteArray ResultContent = QByteArray::fromBase64(fileContent);
	QString strResultContent = ResultContent;

	if(!doc.setContent(strResultContent))
	{
		file.close();
		return false;
	}
	if(doc.isNull())
	{
		file.close();
		return false;
	}

	QDomElement rootElement = doc.documentElement();
	QDomNodeList elementList = rootElement.childNodes();

	for(int i = 0; i < elementList.count(); i ++)
	{
		QDomNode node = elementList.at(i);
		QDomElement element = node.toElement();
		if(element.tagName() == "userInfo")
		{
			QString strName = element.attribute("name");
			QString strPassword = element.attribute("password");
			QString strIndex = element.attribute("index");
			int nIndex = strIndex.toInt();
			QPair<QString,QString> pairUserAndPass;
			pairUserAndPass.first = strName;
			pairUserAndPass.second = strPassword;
			m_hashIndexToUserInfo.insert(nIndex,pairUserAndPass);
		}
	}
	return true;
}

bool HUICLogin::writeConfig()
{
	QString strleUserName = m_plecmbUser->text();
	QString strPassword = m_plePassword->text();

	QHash<int,QPair<QString,QString>> t_hashResultIndexToUserInfo;

	bool t_bFindUser = false;
	for(int nUserInfoIndex = 0; nUserInfoIndex < m_hashIndexToUserInfo.count(); nUserInfoIndex ++)
	{
		QPair<QString,QString> pairUserNameAndPassword = m_hashIndexToUserInfo.value(nUserInfoIndex);
		QString strUserName = pairUserNameAndPassword.first;
		if(strUserName == strleUserName)
		{
			t_bFindUser = true;
			continue;
		}
		if(!t_bFindUser)
		{
			t_hashResultIndexToUserInfo.insert(nUserInfoIndex + 1,pairUserNameAndPassword);
		}
		else
		{
			t_hashResultIndexToUserInfo.insert(nUserInfoIndex,pairUserNameAndPassword);
		}
	}

	if(m_pckbRPassword->checkState() == Qt::Unchecked)
	{
		strPassword = "";
	}
	
	t_hashResultIndexToUserInfo.insert(0,QPair<QString,QString>(strleUserName,strPassword));
	if(t_hashResultIndexToUserInfo.count() > m_nCount)
	{
		t_hashResultIndexToUserInfo.remove(m_nCount);
	}

	QString strFile = g_strAppPath + XMLRELATIONPATH + "userNameConfig.xml";

	QDomDocument doc;
    QDomProcessingInstruction instruction;
    instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
    doc.appendChild(instruction);

    QDomElement root = doc.createElement("userNameConfig");
    doc.appendChild(root);

    QHash<int,QPair<QString,QString>>::iterator mi;
    for(mi = t_hashResultIndexToUserInfo.begin();mi!=t_hashResultIndexToUserInfo.end();mi++)
    {
		QPair<QString,QString> pairUserInfo = mi.value();
		QString strName = pairUserInfo.first;
		QString strPassword = pairUserInfo.second;
		int nIndex = mi.key();
		QString strIndex;

		QDomElement nodecontent = doc.createElement("userInfo");
		nodecontent.setAttribute("name",strName);
		nodecontent.setAttribute("password",strPassword);
		nodecontent.setAttribute("index",strIndex.setNum(nIndex));
		root.appendChild(nodecontent);
    }

    QFile file(g_strAppPath + XMLRELATIONPATH + "userNameConfig.xml");
    if(!file.open(QIODevice::ReadWrite|QIODevice::Truncate|QIODevice::Text))
        return false;

    QTextStream out(&file);
	out.setCodec("UTF-8");
    doc.save(out,4,QDomNode::EncodingFromTextStream);
	
    file.close();

	if(!file.open(QIODevice::ReadWrite))
		return false;

	QByteArray baContent = file.readAll();
	QByteArray baBase64Content = baContent.toBase64(QByteArray::Base64Encoding);
	//QString strContent = (baBase64Content);
	file.resize(0);
	file.write(baBase64Content);

	file.close();

    return true;
}

void HUICLogin::sltUserNameTextChanged(QString strText)
{
	bool bFindUser = false;
	QString strName;
	QString strPassword;
	for(int i = 0; i < m_hashIndexToUserInfo.count(); i ++)
	{
		QPair<QString,QString> pairUserInfo = m_hashIndexToUserInfo.value(i);
		strName = pairUserInfo.first;
		strPassword = pairUserInfo.second;
		if(strText == strName)
		{
			bFindUser = true;
			break;
		}
	}

	if(bFindUser)
	{
		m_plePassword->setText(strPassword);
		m_pckbRPassword->setChecked(strPassword == "" ? false : true);
	}
	else
	{
		m_plePassword->setText("");
		m_pckbRPassword->setChecked(false);
	}

	if(m_plblWarning->text() == WARNINGSTR_USERNAMEANDPASS)
	{
		m_plblWarning->setText("");
	}
}

void HUICLogin::sltLineEditFocusStateChanged(bool bHasFocus)
{
    QObject *t_pobjSender = QObject::sender();
    HLineEdit *t_pLineEdit = dynamic_cast<HLineEdit*>(t_pobjSender);
    if(t_pLineEdit)
    {
        if(bHasFocus)
        {
            t_pLineEdit->setStyleSheet(QString("border-image:url(%1HIDI_LOGIN_LINEEDIT_HOR.png)").arg(g_strAppPath + g_strImageRelationPath));
           // t_pLineEdit->setStyleSheet("background-color:red");border-image:url(%1HIDI_CAPTION_CLOSE_HOR.png);
        }
        else
        {
            t_pLineEdit->setStyleSheet(QString("border-image:url(%1HIDI_LOGIN_LINEEDIT_NOR.png)").arg(g_strAppPath + g_strImageRelationPath));
            //t_pLineEdit->setStyleSheet("background-color:green");
        }

    }
}

void HUICLogin::sltComboBoxFocusStateChanged(bool bHasFocus)
{
    QObject *t_pobjSender = QObject::sender();
    HComboBox *t_pComboBox = dynamic_cast<HComboBox*>(t_pobjSender);
    if(t_pComboBox)
    {
        if(bHasFocus)
        {
            t_pComboBox->setStyleSheet(QString("border-image:url(%1HIDI_LOGIN_LINEEDIT_HOR.png)").arg(g_strAppPath + g_strImageRelationPath));
           // t_pLineEdit->setStyleSheet("background-color:red");border-image:url(%1HIDI_CAPTION_CLOSE_HOR.png);
        }
        else
        {
            t_pComboBox->setStyleSheet(QString("border-image:url(%1HIDI_LOGIN_LINEEDIT_NOR.png)").arg(g_strAppPath + g_strImageRelationPath));
            //t_pLineEdit->setStyleSheet("background-color:green");
        }

    }
}

void HUICLogin::sltComboBoxIndexChanged(QString strText)
{
	for(int cmbIndex = 0; cmbIndex < m_hashIndexToUserInfo.count(); cmbIndex ++)
	{
		QPair<QString,QString> pairUserNameAndPass = m_hashIndexToUserInfo.value(cmbIndex);
		QString strUserName = pairUserNameAndPass.first;
		QString strPassword = pairUserNameAndPass.second;
		if(strUserName == strText)
		{
			m_plePassword->setText(strPassword);
			m_pckbRPassword->setChecked(strPassword == "" ? false : true);
			
		}
	}
}

void HUICLogin::sltLoginBtnClicked()
{
    m_plblWarning->setText(QString::fromLocal8Bit(WARNINGSTR_LOADING));
	m_plblWarning->show();
	this->repaint();

	if(m_plePassword->text() == "" || m_plecmbUser->text() == "")
	{
		m_plblWarning->setText(QString::fromLocal8Bit(WARNINGSTR_USERNAMEORPASSNULL));
		return;
	}

    writeConfig();
    emit sigLoginBtnClicked();
}

void HUICLogin::sltCloseBtnClicked()
{
	HExitPanel *t_pExitPanel = new HExitPanel;
	t_pExitPanel->show();
}
